package com.jdd.modules.parkmonthly.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jdd.common.api.vo.Result;
import com.jdd.common.aspect.annotation.AutoLog;
import com.jdd.common.constant.JddConstant;
import com.jdd.common.util.DateUtil;
import com.jdd.common.util.excel.entity.params.ExportParams;
import com.jdd.common.util.excel.web.entity.vo.NormalExcelConstants;
import com.jdd.common.util.excel.web.view.EasypoiSingleExcelView;
import com.jdd.modules.area.entity.ParkAreaInfo;
import com.jdd.modules.area.service.IParkAreaInfoService;
import com.jdd.modules.parkcar.entity.ParkCarMonthly;
import com.jdd.modules.parkcar.entity.ParkSpace;
import com.jdd.modules.parkcar.service.IParkCarMonthlyService;
import com.jdd.modules.parking.entity.ParkInfo;
import com.jdd.modules.parking.service.IParkInfoService;
import com.jdd.modules.parkmonthly.dto.MonthlyCarDto;
import com.jdd.modules.parkmonthly.dto.MonthlyCardDelayDto;
import com.jdd.modules.parkmonthly.dto.MonthlyCardInfoDTO;
import com.jdd.modules.parkmonthly.entity.MonthlyCarConfig;
import com.jdd.modules.parkmonthly.entity.MonthlyCardInfo;
import com.jdd.modules.parkmonthly.entity.MonthlyDepartment;
import com.jdd.modules.parkmonthly.entity.PermissionArea;
import com.jdd.modules.parkmonthly.entity.PermissionGroup;
import com.jdd.modules.parkmonthly.entity.dto.DownloadMonthlyTempReq;
import com.jdd.modules.parkmonthly.entity.enums.MonthlyTempKind;
import com.jdd.modules.parkmonthly.entity.vo.ExportExcelTempVo;
import com.jdd.modules.parkmonthly.service.IAddMonthlyCardInfoService;
import com.jdd.modules.parkmonthly.service.IDelayMonthlyCardInfoService;
import com.jdd.modules.parkmonthly.service.IEditMonthlyCardInfoService;
import com.jdd.modules.parkmonthly.service.IMonthlyCarConfigService;
import com.jdd.modules.parkmonthly.service.IMonthlyCardInfoImportExtService;
import com.jdd.modules.parkmonthly.service.IMonthlyCardInfoService;
import com.jdd.modules.parkmonthly.service.IMonthlyDepartmentService;
import com.jdd.modules.parkmonthly.service.IPermissionAreaService;
import com.jdd.modules.parkmonthly.service.IPermissionGroupService;
import com.jdd.modules.parkmonthly.service.IRemoveMonthlyCardInfoService;
import com.jdd.modules.parkmonthly.util.ExcelUtils;

import cn.hutool.core.collection.CollectionUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 月卡信息表
 * @Author: jdd
 * @Date: 2021-11-09
 * @Version: V1.0
 */
@Api(tags = "月卡信息表")
@RestController
@RequestMapping("/monthlyCardInfo")
@Slf4j
public class MonthlyCardInfoController {

    @Resource
    private IMonthlyCardInfoService monthlyCardInfoService;
    @Resource
    private IPermissionAreaService iPermissionAreaService;
    @Resource
    private IParkCarMonthlyService parkCarMonthlyService;
    @Resource
    private IParkCarMonthlyService iParkCarMonthlyService;
    @Autowired
    private IMonthlyCarConfigService monthlyCarConfigService;
    @Autowired
    private IPermissionGroupService permissionGroupService;
    @Autowired
    private IParkAreaInfoService parkAreaInfoService;
    @Autowired
    private IMonthlyDepartmentService monthlyDepartmentService;
    @Autowired
    private IParkInfoService parkInfoService;
    @Autowired
    private IAddMonthlyCardInfoService addMonthlyCardInfoService;
    @Autowired
    private IDelayMonthlyCardInfoService delayMonthlyCardInfoService;
    @Autowired
    private IEditMonthlyCardInfoService editMonthlyCardInfoService;
    @Autowired
    private IRemoveMonthlyCardInfoService removeMonthlyCardInfoService;
    @Autowired
    private IMonthlyCardInfoImportExtService monthlyCardInfoImportExtService;

    @Value("${parkInfo.parkCode}")
    private String parkCode;
    /**
     * 月卡状态定时任务
     *
     * @return
     */
    @AutoLog(value = "月卡状态定时任务-更新")
    @ApiOperation(value = "月卡状态定时任务-更新", notes = "月卡状态定时任务-更新")
    @PostMapping(value = "/updateMonthlyCardStatus")
    public void updateMonthlyCardStatus() {
        QueryWrapper<MonthlyCardInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("monthly_status", JddConstant.IntNumber.INT_ONE);
        queryWrapper.eq("del_flag",0);
        List<MonthlyCardInfo> list = monthlyCardInfoService.list(queryWrapper);
        if(CollectionUtils.isEmpty(list)){
            return;
        }
        List<MonthlyCardInfo> updateList = list.stream().filter(s->s.getEndTime().before(new Date())).collect(Collectors.toList());
        updateList.stream().map(o->o.setMonthlyStatus(JddConstant.IntNumber.INT_FOUR));
        if(CollectionUtils.isEmpty(updateList)){
            return;
        }
        monthlyCardInfoService.updateBatchById(updateList);
    }

    /**
     * 添加
     * 月卡信息表-添加
     *
     * @param monthlyCardInfo
     * @return
     */
    @AutoLog(value = "月卡信息表-添加")
    @ApiOperation(value = "月卡信息表-添加", notes = "月卡信息表-添加")
    @RequestMapping(value = "/add")
    public Result<MonthlyCardInfo> add(@RequestBody MonthlyCardInfo monthlyCardInfo) {
        return addMonthlyCardInfoService.add(monthlyCardInfo);
    }


    /**
     * 根据勾选权限，查询出所有权限下未绑定的车位信息
     *
     * @param monthlyCardInfo
     * @return
     */
    @AutoLog(value = "未绑定的车位信息-查询")
    @ApiOperation(value = "未绑定的车位信息-查询", notes = "查询")
    @RequestMapping(value = "/queryUnUseSpace")
    public Result<List<ParkSpace>> queryUnUseSpace(@RequestBody MonthlyCardInfo monthlyCardInfo) {
        return monthlyCardInfoService.queryUnUseSpace(monthlyCardInfo);
    }


    /**
     * 开通延期注销-确认提示
     *
     * @param monthlyCarDto
     * @return
     */
    @AutoLog(value = "开通延期注销-确认提示")
    @ApiOperation(value = "开通延期注销-确认提示", notes = "查询")
    @PostMapping(value = "/delayConfirm")
    public Result<String> delayConfirm(@RequestBody MonthlyCarDto monthlyCarDto) {
        return monthlyCardInfoService.delayConfirm(monthlyCarDto);
    }


    /**
     * 查询编辑该月卡信息绑定的车牌号信息
     *
     * @param monthlyCardInfo
     * @return
     */
    @RequestMapping(value = "/getUpatePlateNoInfo")
    public Result getUpatePlateNoInfo(@RequestBody MonthlyCardInfo monthlyCardInfo) {
        return monthlyCardInfoService.getUpatePlateNoInfo(monthlyCardInfo);
    }


    /**
     * 查询编辑该月卡信息绑定的车位信息
     *
     * @param monthlyCardInfo
     * @return
     */
    @RequestMapping(value = "/getUpateCarPlaceInfo")
    public Result getUpateCarPlaceInfo(@RequestBody MonthlyCardInfo monthlyCardInfo) {
        return monthlyCardInfoService.getUpateCarPlaceInfo(monthlyCardInfo);
    }


    /**
     * 月卡延期
     *
     * @param monthlyCardDelayDto
     * @return
     */
    @RequestMapping(value = "/updateMonthlyCardDelay")
    public Result updateMonthlyCardDelay(@RequestBody MonthlyCardDelayDto monthlyCardDelayDto) {
        return delayMonthlyCardInfoService.updateMonthlyCardDelay(monthlyCardDelayDto);
    }


    /**
     * 注销月卡信息
     *
     * @param monthlyCardInfo
     * @return
     */
    @RequestMapping(value = "/getMonthlyCardConcel")
    public Result getMonthlyCardConcel(@RequestBody MonthlyCardInfo monthlyCardInfo) {
        return removeMonthlyCardInfoService.getMonthlyCardConcel(monthlyCardInfo);
    }


    /**
     * 编辑
     *
     * @param monthlyCardInfo
     * @return
     */
    @AutoLog(value = "月卡信息表-编辑")
    @ApiOperation(value = "月卡信息表-编辑", notes = "月卡信息表-编辑")
    @PutMapping(value = "/edit")
    public Result<MonthlyCardInfo> edit(@RequestBody MonthlyCardInfo monthlyCardInfo) {
        return editMonthlyCardInfoService.editMonthlyCard(monthlyCardInfo);
    }


    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "月卡信息表-通过id查询")
    @ApiOperation(value = "月卡信息表-通过id查询", notes = "月卡信息表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<MonthlyCardInfo> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<MonthlyCardInfo> result = new Result<MonthlyCardInfo>();
        MonthlyCardInfo monthlyCardInfo = monthlyCardInfoService.getById(id);
        if (monthlyCardInfo == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(monthlyCardInfo);
            result.setSuccess(true);
        }
        return result;
    }


    /**
     * 权限列表-查询
     *
     * @param parkCode
     * @return
     */
    @AutoLog(value = "权限列表-查询")
    @ApiOperation(value = "权限列表-查询", notes = "权限列表-查询")
    @RequestMapping(value = "/queryPermissionList")
    public Result<List<PermissionArea>> queryPermissionList(String parkCode) {
        Result<List<PermissionArea>> result = new Result<>();
        QueryWrapper<PermissionArea> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("park_code", parkCode);
        List<PermissionArea> list = iPermissionAreaService.list(queryWrapper);
        result.setResult(list);
        result.setSuccess(true);
        return result;
    }


    /**
     * 查询车牌号是否已经绑定月卡
     * 月卡信息表-添加
     *
     * @param monthlyCarDto
     * @return
     */
    @AutoLog(value = "查询车牌号是否已经绑定月卡")
    @ApiOperation(value = "查询车牌号是否已经绑定月卡", notes = "查询车牌号是否已经绑定月卡")
    @PostMapping(value = "/queryCarInUse")
    public Result<String> queryCarInUse(@RequestBody MonthlyCarDto monthlyCarDto) {
        Result<String> result = new Result<>();
        if (CollectionUtils.isEmpty(monthlyCarDto.getPlateNoList())) {
            return result;
        }
        String stringBuilder = null;
        QueryWrapper<ParkCarMonthly> parkCarMonthlyQueryWrapper = new QueryWrapper<>();
        parkCarMonthlyQueryWrapper.eq("park_code", monthlyCarDto.getParkCode());
        parkCarMonthlyQueryWrapper.in("plate_no", monthlyCarDto.getPlateNoList());
        parkCarMonthlyQueryWrapper.in("status","Y");
        List<ParkCarMonthly> parkCarMonthlyList = iParkCarMonthlyService.list(parkCarMonthlyQueryWrapper);
        if (CollectionUtils.isNotEmpty(parkCarMonthlyList)) {
            List<String> platNos = parkCarMonthlyList.stream().map(ParkCarMonthly::getPlateNo).distinct().collect(Collectors.toList());
            String parkNumber = org.apache.commons.lang3.StringUtils.join(platNos.toArray(), ",");
            stringBuilder = "车牌号：" + parkNumber + "存在月租车中";
            result.setSuccess(false);
            result.setMessage(stringBuilder);
            return result;
        }
        result.setSuccess(true);
        result.setMessage(stringBuilder);
        return result;
    }


    /**
     * 月卡信息表-分页列表查询"
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @AutoLog(value = "月卡信息表-分页列表查询")
    @ApiOperation(value = "月卡信息表-分页列表查询", notes = "月卡信息表-分页列表查询")
    @RequestMapping(value = "/list")
    public Result<IPage<MonthlyCardInfoDTO>> queryPageList(MonthlyCardInfoDTO monthlyCardInfoDTO,
                                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                           @RequestParam(name = "createTime_begin", required = false) String createTimeBegin,
                                                           @RequestParam(name = "createTime_end", required = false) String createTimeEnd,
                                                           HttpServletRequest req) {
        log.info("------------------>:{}", monthlyCardInfoDTO);
        Result<IPage<MonthlyCardInfoDTO>> result = new Result<>();
        QueryWrapper<MonthlyCardInfoDTO> queryWrapper = new QueryWrapper<>();

        
        // 有无park_code
        queryWrapper.eq("monthly_card_info.park_code", parkCode);
        String needQueryWithCondition = "0";
        QueryWrapper<MonthlyCardInfo> monthlyCardInfoQueryWrapper = new QueryWrapper<>();
        // 月租编号模糊查询
        if (StringUtils.isNotBlank(monthlyCardInfoDTO.getMonthlyCode())) {
            needQueryWithCondition = "1";
            monthlyCardInfoQueryWrapper.lambda().like(MonthlyCardInfo::getMonthlyCode, monthlyCardInfoDTO.getMonthlyCode());
        }
        // 车主名称模糊查询
        if (StringUtils.isNotBlank(monthlyCardInfoDTO.getCarOwnerName())) {
            needQueryWithCondition = "1";
            monthlyCardInfoQueryWrapper.lambda().like(MonthlyCardInfo::getCarOwnerName, monthlyCardInfoDTO.getCarOwnerName());
        }
        // 月租套餐查询
        if (StringUtils.isNotBlank(monthlyCardInfoDTO.getPackageId())) {
            needQueryWithCondition = "1";
            monthlyCardInfoQueryWrapper.lambda().eq(MonthlyCardInfo::getPackageId, monthlyCardInfoDTO.getPackageId());
        }
        // 通行权限查询
        if (StringUtils.isNotBlank(monthlyCardInfoDTO.getThroughAuthorityId())) {
            needQueryWithCondition = "1";
            monthlyCardInfoQueryWrapper.lambda().eq(MonthlyCardInfo::getThroughAuthorityId, monthlyCardInfoDTO.getThroughAuthorityId());
        }
        // 部门组织查询
        if (StringUtils.isNotBlank(monthlyCardInfoDTO.getMonthlyDepartmentId())) {
            needQueryWithCondition = "1";
            monthlyCardInfoQueryWrapper.lambda().eq(MonthlyCardInfo::getMonthlyDepartmentId, monthlyCardInfoDTO.getMonthlyDepartmentId());
        }
        // 手机尾号模糊匹配
        if (StringUtils.isNotBlank(monthlyCardInfoDTO.getTelephone())) {
            needQueryWithCondition = "1";
            monthlyCardInfoQueryWrapper.like("monthly_card_info.telephone", monthlyCardInfoDTO.getTelephone());
        }
        // 操作到期时间匹配
        if (StringUtils.isNotBlank(createTimeBegin)) {
            needQueryWithCondition = "1";
            monthlyCardInfoQueryWrapper.ge("monthly_card_info.end_time", DateUtil.fomatDateTime(createTimeBegin));
        }
        if (StringUtils.isNotBlank(createTimeEnd)) {
            log.info("===============>：{}", createTimeEnd);
            needQueryWithCondition = "1";
            monthlyCardInfoQueryWrapper.le("monthly_card_info.end_time", DateUtil.fomatDateTime(createTimeEnd));
        }

        log.info("needQueryWithCondition------------>:{}",needQueryWithCondition);
        if (needQueryWithCondition.equals("1")) {
            List<String> monthlyCardInfoIds = monthlyCardInfoService.getIds(monthlyCardInfoQueryWrapper).stream().distinct().collect(Collectors.toList());
            if (CollectionUtil.isEmpty(monthlyCardInfoIds)) {
                return result;
            } else {
                queryWrapper.in("monthly_card_info.id", monthlyCardInfoIds);
            }
        }
        QueryWrapper<ParkCarMonthly> plateNoQueryWrapper = new QueryWrapper<>();
        needQueryWithCondition = "0";
        // 车牌号模糊查询 ,车位号模糊查询
        if (StringUtils.isNotBlank(monthlyCardInfoDTO.getPlateNo())) {
            needQueryWithCondition = "1";
            plateNoQueryWrapper.lambda().like(ParkCarMonthly::getPlateNo, monthlyCardInfoDTO.getPlateNo());
        }
        if (StringUtils.isNotBlank(monthlyCardInfoDTO.getParkNumber())) {
            needQueryWithCondition = "1";
            plateNoQueryWrapper.lambda().like(ParkCarMonthly::getParkNumber, monthlyCardInfoDTO.getParkNumber());
        }
        if (needQueryWithCondition.equals("1")) {
            List<String> monthlyCardInfoIds = parkCarMonthlyService.monthlyCarInfoIds(plateNoQueryWrapper).stream().distinct().collect(Collectors.toList());
            if (CollectionUtil.isEmpty(monthlyCardInfoIds)) {
                return result;
            } else {
                queryWrapper.in("monthly_card_info.id", monthlyCardInfoIds);
            }
        }
        Page<MonthlyCardInfoDTO> page = new Page<>(pageNo, pageSize);
        IPage<MonthlyCardInfoDTO> iPage = parkCarMonthlyService.monthlyCarInfoList(page, queryWrapper);
        List<MonthlyCardInfoDTO> dealRecord = iPage.getRecords();
        if (CollectionUtils.isNotEmpty(dealRecord)){
            int dayLin = 30;
            MonthlyCarConfig monthlyCarConfig = monthlyCarConfigService.queryByParkCode(parkCode).getResult();
            if(monthlyCarConfig != null){
                dayLin = Integer.valueOf(monthlyCarConfig.getPeriodMonthlyDays());
            }
            
            LambdaQueryWrapper<MonthlyDepartment> deptQueryWrapper = Wrappers.lambdaQuery();
            deptQueryWrapper.eq(MonthlyDepartment::getDelFlag, JddConstant.IntNumber.INT_ZERO);
            List<MonthlyDepartment> deptList = monthlyDepartmentService.list(deptQueryWrapper);
        for (MonthlyCardInfoDTO monthlyCardInfoDTO1:dealRecord){

           //根据部门id查询当前部门的所有上级部门并拼接返回
           String departmentNameChain = monthlyDepartmentService.getDepartmentNameChain(monthlyCardInfoDTO1.getMonthlyDepartmentId());
           //String deptTreeName = this.getDeptTree(deptList, monthlyCardInfoDTO1.getMonthlyDepartmentId(), "");
           monthlyCardInfoDTO1.setMonthlyDepartmentName(departmentNameChain);

           
           //先判断是否过期，过期设为0
            if(System.currentTimeMillis() > monthlyCardInfoDTO1.getEndTime().getTime()){
                //过期
                monthlyCardInfoDTO1.setIsLay(JddConstant.StringNumber.STRING_ZERO);
                continue;
            }
                int days = DateUtil.differentDaysByMillisecond(new Date(), monthlyCardInfoDTO1.getEndTime());
//                if (days < 0) {
//                    monthlyCardInfoDTO1.setIsLay(JddConstant.StringNumber.STRING_ZERO);
//                    continue;
//                }
                if (days < dayLin) {
                    monthlyCardInfoDTO1.setIsLay(JddConstant.StringNumber.STRING_ONE);
                    continue;
                }
                monthlyCardInfoDTO1.setIsLay(JddConstant.StringNumber.STRING_THREE);

        }
        }
        iPage.setRecords(dealRecord);
        result.setResult(iPage);
        return result;
    }
    
    /** 获取部门信息 */
    private String getDeptTree(List<MonthlyDepartment> deptList,String deptSonId,String result){
    	if(CollectionUtils.isEmpty(deptList)){
    		return "";
    	}
    	for(MonthlyDepartment dept : deptList){
    		if(dept.getId().equals(deptSonId)){
    			if(StringUtils.isNotBlank(result)){
    				result = result + "," + dept.getDepartName();
    			}else{
    				result = dept.getDepartName();
    			}
    			if(dept.getDepartType() == JddConstant.IntNumber.INT_ZERO){
    				return result;
    			}
    			deptSonId = dept.getParentId();
    			return getDeptTree(deptList, deptSonId, result);
    		}
    	}
    	return null;
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response, MonthlyCardInfoDTO monthlyCardInfoDTO, String createTimeBegin,
                                  String createTimeEnd) {
        // Step.1 组装查询条件
        QueryWrapper<MonthlyCardInfoDTO> queryWrapper = new QueryWrapper<>();

        // 有无park_code
        queryWrapper.eq("monthly_card_info.park_code", parkCode);
        String needQueryWithCondition = "0";
        QueryWrapper<MonthlyCardInfo> monthlyCardInfoQueryWrapper = new QueryWrapper<>();
        // 月租编号模糊查询
        if (StringUtils.isNotBlank(monthlyCardInfoDTO.getMonthlyCode())) {
            needQueryWithCondition = "1";
            monthlyCardInfoQueryWrapper.lambda().like(MonthlyCardInfo::getMonthlyCode, monthlyCardInfoDTO.getMonthlyCode());
        }
        // 车主名称模糊查询
        if (StringUtils.isNotBlank(monthlyCardInfoDTO.getCarOwnerName())) {
            needQueryWithCondition = "1";
            monthlyCardInfoQueryWrapper.lambda().like(MonthlyCardInfo::getCarOwnerName, monthlyCardInfoDTO.getCarOwnerName());
        }
        // 月租套餐查询
        if (StringUtils.isNotBlank(monthlyCardInfoDTO.getPackageId())) {
            needQueryWithCondition = "1";
            monthlyCardInfoQueryWrapper.lambda().eq(MonthlyCardInfo::getPackageId, monthlyCardInfoDTO.getPackageId());
        }
        // 通行权限查询
        if (StringUtils.isNotBlank(monthlyCardInfoDTO.getThroughAuthorityId())) {
            needQueryWithCondition = "1";
            monthlyCardInfoQueryWrapper.lambda().eq(MonthlyCardInfo::getThroughAuthorityId, monthlyCardInfoDTO.getThroughAuthorityId());
        }
        // 部门组织查询
        if (StringUtils.isNotBlank(monthlyCardInfoDTO.getMonthlyDepartmentId())) {
            needQueryWithCondition = "1";
            monthlyCardInfoQueryWrapper.lambda().eq(MonthlyCardInfo::getMonthlyDepartmentId, monthlyCardInfoDTO.getMonthlyDepartmentId());
        }
        // 手机尾号模糊匹配
        if (StringUtils.isNotBlank(monthlyCardInfoDTO.getTelephone())) {
            needQueryWithCondition = "1";
            monthlyCardInfoQueryWrapper.likeLeft("monthly_card_info.telephone", monthlyCardInfoDTO.getTelephone());
        }
        // 操作到期时间匹配
        if (StringUtils.isNotBlank(createTimeBegin)) {
            needQueryWithCondition = "1";
            monthlyCardInfoQueryWrapper.ge("monthly_card_info.end_time", DateUtil.fomatDateTime(createTimeBegin));
        }
        if (StringUtils.isNotBlank(createTimeEnd)) {
            log.info("===============>：{}", createTimeEnd);
            needQueryWithCondition = "1";
            monthlyCardInfoQueryWrapper.le("monthly_card_info.end_time", DateUtil.fomatDateTime(createTimeEnd));
        }

        if (needQueryWithCondition.equals("1")) {
            List<String> monthlyCardInfoIds = monthlyCardInfoService.getIds(monthlyCardInfoQueryWrapper).stream().distinct().collect(Collectors.toList());
            if (CollectionUtil.isEmpty(monthlyCardInfoIds)) {
                ModelAndView mv = new ModelAndView(new EasypoiSingleExcelView());
                List<MonthlyCardInfo> pageList = new ArrayList<>();
                //导出文件名称
                mv.addObject(NormalExcelConstants.FILE_NAME, "月卡信息表列表");
                mv.addObject(NormalExcelConstants.CLASS, MonthlyCardInfo.class);
                mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("月卡信息表数据", "导出信息"));
                mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
                return mv;
            } else {
                queryWrapper.in("monthly_card_info.id", monthlyCardInfoIds);
            }
        }
        QueryWrapper<ParkCarMonthly> plateNoQueryWrapper = new QueryWrapper<>();
        needQueryWithCondition = "0";
        // 车牌号模糊查询 ,车位号模糊查询
        if (StringUtils.isNotBlank(monthlyCardInfoDTO.getPlateNo())) {
            needQueryWithCondition = "1";
            plateNoQueryWrapper.lambda().like(ParkCarMonthly::getPlateNo, monthlyCardInfoDTO.getPlateNo());
        }
        if (StringUtils.isNotBlank(monthlyCardInfoDTO.getParkNumber())) {
            needQueryWithCondition = "1";
            plateNoQueryWrapper.lambda().like(ParkCarMonthly::getPlateNo, monthlyCardInfoDTO.getParkNumber());
        }
        if (needQueryWithCondition.equals("1")) {
            List<String> monthlyCardInfoIds = parkCarMonthlyService.monthlyCarInfoIds(plateNoQueryWrapper).stream().distinct().collect(Collectors.toList());
            if (CollectionUtil.isEmpty(monthlyCardInfoIds)) {
                ModelAndView mv = new ModelAndView(new EasypoiSingleExcelView());
                List<MonthlyCardInfo> pageList = new ArrayList<>();
                //导出文件名称
                mv.addObject(NormalExcelConstants.FILE_NAME, "月卡信息表列表");
                mv.addObject(NormalExcelConstants.CLASS, MonthlyCardInfo.class);
                mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("月卡信息表列表数据", "导出信息"));
                mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
                return mv;
            } else {
                queryWrapper.in("monthly_card_info.id", monthlyCardInfoIds);
            }
        }
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new EasypoiSingleExcelView());
        List<MonthlyCardInfoDTO> list = new ArrayList<>();
        List<MonthlyCardInfoDTO> pageList = parkCarMonthlyService.monthlyCarInfo(list, queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "月卡信息表列表");
        mv.addObject(NormalExcelConstants.CLASS, MonthlyCardInfoDTO.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("月卡信息表列表数据", "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }
    
    /**
     * 月卡导入模板下载
     *
     * @param request
     * @param
     */
    @AutoLog(value = "月卡导入模板下载")
    @ApiOperation(value = "月卡导入模板下载", notes = "月卡导入模板下载")
    @RequestMapping(value = "/downloadTemp")
    public void exportXls(HttpServletResponse response,HttpServletRequest request) {
    	List<ExportExcelTempVo> list = new ArrayList<ExportExcelTempVo>();
		list.add(this.getFirstLineExcelInfo());
    	// 导出操作
    	ExcelUtils.exportExcel(list, null, "sheet1", ExportExcelTempVo.class, "月租车导入模板.xls", response, request);
    }
    
    /** 组装第一行数据 */
    private ExportExcelTempVo getFirstLineExcelInfo(){
    	return ExportExcelTempVo.builder()
    			.plateNo(MonthlyTempKind.PLATENO.value())
    			.parkNumbers(MonthlyTempKind.PARKNUMBERS.value())
    			.startTime(MonthlyTempKind.STARTTIME.value())
    			.endTime(MonthlyTempKind.ENDTIME.value())
    			.money(MonthlyTempKind.MONEY.value())
    			.ownerName(MonthlyTempKind.OWNERNAME.value())
    			.phoneNumber(MonthlyTempKind.PHONENUMBER.value())
    			.roomNumber(MonthlyTempKind.ROOMNUMBER.value())
    			.remarks(MonthlyTempKind.REMARKS.value())
    			.build();
    }
    
    /**
     * 文件检查
     * @return
     */
    @AutoLog(value = "文件检查")
    @ApiOperation(value = "文件检查", notes = "文件检查")
    @PostMapping(value = "/fileInspect")
    public Result<?> fileInspect(@Valid @ModelAttribute final DownloadMonthlyTempReq req, 
    		final BindingResult bindingResult,HttpServletRequest request) {
    	try {
    		if(bindingResult.hasErrors()){
    			return Result.validError(bindingResult);
    		}
    		Result<String> result = new Result<>();
    		result = this.verifyParame(req);
    		if(result.getCode() != 0){
    			return Result.error(result.getMessage());
    		}
    		monthlyCardInfoImportExtService.verifyImportFile(req,request);
			return Result.ok();
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error(e.getMessage());
		}
    }
    
    /**
     * 导入月租车
     * @return
     */
    @AutoLog(value = "导入EXCEL")
    @ApiOperation(value = "导入EXCEL", notes = "导入EXCEL")
    @PostMapping(value = "/importExcel")
    public Result<?> importMonthlyExcel(@Valid @ModelAttribute final DownloadMonthlyTempReq req, 
    		final BindingResult bindingResult,HttpServletRequest request) {
    	try {
    		if(bindingResult.hasErrors()){
    			return Result.validError(bindingResult);
    		}
    		Result<String> result = new Result<>();
    		result = this.verifyParame(req);
    		if(result.getCode() != 0){
    			return Result.error(result.getMessage());
    		}
    		boolean flag = monthlyCardInfoImportExtService.importMonthlyExcel(req,request);
    		if(flag){
    			return Result.ok();
    		}else{
    			return Result.error("导入失败");
    		}
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error(e.getMessage());
		}
    }
    
    /** 验证条件是否成立 */
    private Result<String> verifyParame(DownloadMonthlyTempReq req){
    	// 验证车场是否存在
    	if(!this.isPark(req.getParkCode())){
    		return Result.error("车场不存在，请从新选择");
    	}
    	// 验证通行权限是否存在
    	if(StringUtils.isNotBlank(req.getThroughAuthorityId()) && !this.isThroughAuthority(req.getThroughAuthorityId())){
    		return Result.error("通行权限不存在，请从新选择");
    	}
    	// 验证区域是否存在
    	if(!this.isArea(req.getAreaId())){
    		return Result.error("车场区域不存在，请从新选择");
    	}
    	// 验证部门是否存在
    	if(!this.isDept(req.getDeptId())){
    		return Result.error("部门不存在，请从新选择");
    	}
    	return new Result<>();
    }
    
    /** 验证部门是否存在 */
    private boolean isDept(String deptId){
    	MonthlyDepartment result = monthlyDepartmentService.getById(deptId);
    	return result != null ? true : false;
    }
    
    /** 验证通行权限是否存在 */
    private boolean isArea(String areaId){
    	ParkAreaInfo result = parkAreaInfoService.getById(areaId);
    	return result != null ? true : false;
    }
    
    /** 验证通行权限是否存在 */
    private boolean isThroughAuthority(String throughAuthorityId){
    	PermissionGroup result = permissionGroupService.getById(throughAuthorityId);
    	return result != null ? true : false;
    }
    
    /** 验证车场是否存在 */
    private boolean isPark(String parkCode){
    	LambdaQueryWrapper<ParkInfo> queryWrapper = Wrappers.lambdaQuery();
    	queryWrapper.eq(ParkInfo::getParkCode, parkCode);
    	int result = parkInfoService.count(queryWrapper);
    	return result > 0 ? true : false;
    }

}
